/*
 * A modified QuizWidget which shows various instructor videos.
 * The user selects the one which most accurately describes
 * the given phrase.
 */

#include <QtGui>

#include "quizdemowidget.h"

// construct quiz demo widget
QuizDemoWidget::QuizDemoWidget(QWidget* parent) : QuizWidget(parent), letters("ABCDEFG") {
    // init fields
    returnLayout = 0;
    phononWidget = 0;
    clip = 0;

    selected = 0;

    phononHook = new QFrame();
    phononHook->setFrameStyle(QFrame::Box | QFrame::Raised);

    connect(this, SIGNAL(correct()), this, SLOT(videoFinished()));
    connect(this, SIGNAL(wrong()), this, SLOT(videoFinished()));
}

// create a pushbutton for a Phrase which displays the Phrase's icon
QAbstractButton* QuizDemoWidget::createButton(Phrase phrase, int buttonIndex) {
    //static int buttonCounter = 0;
    // find numerical order of phrase
    //int index = phrases.indexOf(phrase);
    // show corresponding letter (A, B, C or D)
    QPushButton* newButton = new QPushButton(letters.at(buttonIndex));
    // connect so that we stop playing videos when an option is selected
    //connect(newButton, SIGNAL(clicked()), this, SLOT(stopPlayingVideos()));
    //buttonCounter++;
    return newButton;
}

// lay the buttons onto an (n x 2) grid layout
QLayout* QuizDemoWidget::createOptionsLayout(const QList<QAbstractButton*> options) {
    QHBoxLayout *outerLayout = new QHBoxLayout();
    // get the standard, vertical box layout from QuizWidget

    // push buttons down a bit so there is space for the wording.
    QVBoxLayout *layout = new QVBoxLayout();
    layout->addStretch();
    layout->addSpacing(30);
    //layout->addWidget(new QLabel("Select the option whose video\nmost accurately describes the\ngiven phrase."));
    QListIterator<QAbstractButton*> it(options);
    while (it.hasNext()) {
            layout->addWidget(it.next());
    }
    layout->addStretch();
    //return layout;

    //QLayout* layout = QuizWidget::createOptionsLayout(options);
    // add a hook for the phonon widget
    layout->setMargin(40);
    outerLayout->addLayout(layout);
    outerLayout->addWidget(phononHook);
    return outerLayout;
}

// set the phonon video widget which we will use to display videos.
void QuizDemoWidget::setPhononWidget(Phonon::VideoWidget* widget, QLayout* layout, Phonon::MediaObject* c) {
    // store variables
    phononWidget = widget;
    returnLayout = layout;
    // create a media object for our videos
    clip = /*new Phonon::MediaObject(this);*/c;
    // create a path to the widget
    //path = Phonon::createPath(clip, phononWidget);
    // connect up the slots
    connect(clip, SIGNAL(finished()), this, SLOT(videoFinished()));
    connect(    clip, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
                this, SLOT(phononStateChanged(Phonon::State,Phonon::State)) );

    // reparent the phonon video widget to the hook
    //phononWidget->setParent(phononHook);
    //phononWidget->setFixedSize(VIDEO_SIZE, VIDEO_SIZE);
    QHBoxLayout *layout1 = new QHBoxLayout();
    layout1->addWidget(phononWidget);
    //layout1->setMargin(50);
    phononHook->setLayout(layout1);
}

// the demo video has finished playing
void QuizDemoWidget::videoFinished() {
    // clear this video's 'playing' icon)
    QList<Phrase>::iterator prevPhrase = currentPhrase;
    prevPhrase--;
    // find the button for the phrase video which was previously playing
    QAbstractButton* button = phraseToButtonMap[*prevPhrase];
    // clear icon
    button->setIcon(QIcon());
    // move to next option video
    if (selected != 0) {
        // must stop and play to restart video from beginning
        clip->stop();
        clip->play();
        return;
    } else {
        // don't touch stylesheet if this is real answer
        button->setStyleSheet(""); // clear stylesheet
    }
    playNextPhrase();
}

// the demo video has finished loading
void QuizDemoWidget::phononStateChanged(Phonon::State newState, Phonon::State oldState) {
    if (oldState == Phonon::LoadingState) {
        // just finished loading.
        // don't need to listen for 'loading' state change anymore
        disconnect(this, SLOT(phononStateChanged(Phonon::State,Phonon::State)));
        // automatically begin playing video.
        clip->play();
    }
}

// play the possible answer videos to the user one by one
void QuizDemoWidget::playOptions() {
    clip->clear();
    // start at the first phrase
    currentPhrase = phrases.begin();
    playNextPhrase();
}

// show the next option video
void QuizDemoWidget::playNextPhrase() {
    if (0 != selected)
        return;
    if (currentPhrase == phrases.end()) {
        // loop back to start again
        currentPhrase = phrases.begin();
    }
    // listen for 'loading completed' state change
    connect(    clip, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
                this, SLOT(phononStateChanged(Phonon::State,Phonon::State)));
    // begin loading video.
    // playback will begin automatically in phononStateChanged()
    clip->stop();
    clip->clear();
    clip->setCurrentSource(Phonon::MediaSource("videos/"+currentPhrase->getVideoFilename()));

    // show the 'playing' icon next to the button of the phrase which is playing
    QAbstractButton* button = phraseToButtonMap.value(*currentPhrase);
    QIcon icon;
    icon.addFile(QString::fromUtf8(":/images/images/Play Green.png"), QSize(), QIcon::Normal, QIcon::Off);
    button->setIcon(icon);
    button->setStyleSheet("background: lightblue;");

    // move to next phrase
    currentPhrase++;
}

// stop playing the option demo videos
void QuizDemoWidget::answerSelected() {
    qDebug() << "stop playing videos";
    // reset button colours
    foreach (QAbstractButton* button, buttonList) {
        button->setStyleSheet("");
    }

    // disconnect the status observers, which will break
    // the cyclic chain of videos
    //disconnect(clip, SIGNAL(finished()), this, SLOT(videoFinished()));
    //disconnect(this, SLOT(phononStateChanged(Phonon::State,Phonon::State)));
    // stop the currently playing video.
    // start playing the correct video
    connect(    clip, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
                this,SLOT(phononStateChanged(Phonon::State,Phonon::State))  );
    clip->setCurrentSource("videos/"+answer.getVideoFilename());
}

// return phonon widget to designated recipient.
// invoked when done button clicked
void QuizDemoWidget::cleanup() {
    qDebug() << "cleaning up..." << endl;
    // if we have a phonon widget
    if ((phononWidget != 0) && (returnLayout != 0)) {
        // return phonon widget to the designated layout
        returnLayout->addWidget(phononWidget);
        // erase from our memory
        phononWidget = 0;
        returnLayout = 0;
        // stop and clear the clip
        clip->stop();
        clip->clear();
    }
}

void QuizDemoWidget::paintEvent(QPaintEvent *event) {
    QuizWidget::paintEvent(event);
    // do some painting of our own
    QPainter p(this);
    // note: manual layout. relies on spacing
    // created in createOptionsLayout()
    int x = buttonList.front()->x() - 35;
    p.drawText(x, 70, "Select the option whose video");
    p.drawText(x, 82, "describes the given phrase.");

    // draw the lesson near the last button
    int size = buttonList.front()->width();
    p.drawImage(QRect(buttonList.front()->x(), buttonList.back()->y()+buttonList.back()->height()+10,size,size), icon);
}

void QuizDemoWidget::setImage(QImage img) {
    icon = img;
}

QuizDemoWidget::~QuizDemoWidget() {

}
